package com.xudow.app.dynamicstate_old.module.guide;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.jude.utils.JUtils;
import com.xudow.app.R;
import com.xudow.app.dynamicstate_old.data.DynamicModel;
import com.xudow.app.dynamicstate_old.data.server.ErrorTransform;
import com.xudow.app.dynamicstate_old.domain.entity.Grade;
import com.xudow.app.dynamicstate_old.widget.CircleTextView;
import com.xudow.app.util.PrefUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by ske on 2016/6/7.
 * 第二步
 */
public class ClazzActivity extends AppCompatActivity {
    @BindView(R.id.recyclerview)
    EasyRecyclerView recyclerview;
    @BindView(R.id.next)
    Button next;

    TagAdapter adapter;

    List<Grade> selectedAttention;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_guide_clazz);
        ButterKnife.bind(this);

        setupView();
    }

    @OnClick(R.id.back)
    void back(View view) {
        finish();
    }

    boolean isStudent;

    private void setupView() {
        isStudent = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("isStudent", false);
        selectedAttention = new ArrayList<Grade>();
        GridLayoutManager manager = new GridLayoutManager(this, 3);
        recyclerview.setLayoutManager(manager);
//        recyclerview.addItemDecoration(new SpacesItemDecoration(getResources().getDimensionPixelSize(R.dimen.content_margin)));
        recyclerview.setAdapter(adapter = new TagAdapter(this));
        next.setTextColor(getResources().getColor(isStudent ? R.color.role_student : R.color.role_parent));
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (selectedAttention.size() > 0 || lastPos != -1) {
                    setAttentionType();
                } else {
                    Toast.makeText(ClazzActivity.this, "选择", Toast.LENGTH_SHORT).show();
                }
            }
        });
        getClazz();
    }

    private void setAttentionType() {
        int size = selectedAttention.size();
        long[] data = new long[size];
        for (int i = 0; i < size; i++) {
            data[i] = selectedAttention.get(i).getId();
        }

//        SharedPreferences.Editor editor = this.getSharedPreferences("userInfo",Context.MODE_PRIVATE).edit();
//
//
//        editor.putInt("Status_size",selectedAttention.size()); /*sKey is an array*/
//        Log.i("njbd", "sssssssssssssss22" + size);
//        for(int i=0;i<selectedAttention.size();i++) {
//
//            editor.putString("Status" + i, selectedAttention.get(i).getName());
//            editor.putString("StatusID" + i, String.valueOf(selectedAttention.get(i).getId()));
//        }
//
//       editor.commit();


        String attentiontypeIds = new GsonBuilder()
                .excludeFieldsWithoutExposeAnnotation()
                .create()
                .toJson(data);
        PreferenceManager.getDefaultSharedPreferences(this).edit().putString("Grade", new Gson().toJson(selectedAttention)).apply();
        PreferenceManager.getDefaultSharedPreferences(this).edit().putString("GradeIds", attentiontypeIds).apply();
//        PrefUtils.removeFirstLaunch(this);
        Intent intent = new Intent(ClazzActivity.this, TagActivity.class);
        intent.putExtra("isLogin", getIntent().getBooleanExtra("isLogin", false));
        startActivityForResult(intent, 10086);
    }

    private void getClazz() {
        DynamicModel.getInstance().loadGrades()
                .compose(new ErrorTransform<>(ErrorTransform.ServerErrorHandler.TOAST))
                .subscribe(list -> {
                    adapter.clear();
                    adapter.addAll(list);
                    adapter.notifyDataSetChanged();
                });
    }

    class TagAdapter extends RecyclerArrayAdapter<Grade> {

        public TagAdapter(Context context) {
            super(context);
        }

        @Override
        public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
            return new TagViewHolder(parent);
        }
    }

    Grade lastSelected = new Grade();
    int lastPos = -1;
    int i;
    class TagViewHolder extends BaseViewHolder<Grade> {

        @BindView(R.id.text_tag)
        CircleTextView tag;

        public TagViewHolder(ViewGroup parent) {
            super(parent, R.layout.item_guide_tag);
            ButterKnife.bind(this, itemView);
        }

        @Override
        public void setData(final Grade data) {
            tag.setText(data.getName());
            setBackGround(data.isSelected());

            SharedPreferences sharedPreferences = ClazzActivity.this.getSharedPreferences("nianjiid", Context.MODE_PRIVATE);

            tag.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (isStudent) {
                        if (lastPos != getAdapterPosition()) {
                            lastSelected.setSelected(false);
                            data.setSelected(true);
                            lastSelected = data;
                            adapter.notifyItemChanged(lastPos);
                            adapter.notifyItemChanged(getAdapterPosition());
                            lastPos = getAdapterPosition();
                            selectedAttention.clear();
                            selectedAttention.add(data);
                            SharedPreferences.Editor editor=sharedPreferences.edit();

                            editor.putInt("datagetId" + i, data.getId()); /*sKey is an array*/

                            i++;
                            editor.putInt("datasize", i);
                            editor.commit();
                        }
                    } else {
                        data.setSelected(!data.isSelected());
                        setBackGround(data.isSelected());
                        if (selectedAttention.contains(data)) {
                            selectedAttention.remove(data);
                            SharedPreferences.Editor editor = sharedPreferences.edit();
                            --i;
                            editor.remove("datagetType" + i);
                            editor.remove("datagetId" + i);
                            editor.remove("datasize" + i);
                            //editor.clear();
                            editor.commit();
                        } else {
                            selectedAttention.add(data);

                            SharedPreferences.Editor editor=sharedPreferences.edit();


                            editor.putInt("datagetId" + i, data.getId()); /*sKey is an array*/

                            i++;
                            editor.putInt("datasize", i);
                            editor.commit();

                        }
                    }
                }
            });
        }

        private void setBackGround(boolean select) {
            if (select) {
                if (isStudent) {
                    tag.setBackgroundColor(getResources().getColor(R.color.role_student));
                    tag.setBorderColor(getResources().getColor(R.color.role_student));
                } else {
                    tag.setBackgroundColor(getResources().getColor(R.color.role_parent));
                    tag.setBorderColor(getResources().getColor(R.color.role_parent));
                }
                tag.setTextColor(getResources().getColor(R.color.white));
            } else {
                tag.setBackgroundColor(getResources().getColor(R.color.white));
                tag.setBorderColor(getResources().getColor(R.color.grey));
                tag.setTextColor(getResources().getColor(R.color.gray));
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10086 && resultCode == RESULT_OK) {
            setResult(RESULT_OK);
            finish();
        }
    }
}